import typeOfUtils from "./type-of-utils";
import {Route, RouteRecordPublic, VueRouter} from "vue-router/types/router";
import {filterDuplicates} from "./ArrayUtils";

export class VueUtils {

  /**
   * 设置值
   * @param vm {Vue} vue组件实例
   * @param value
   * @param key {String}
   * this.form.data = value ====> setValueFromVm(this,value,'form.data')
   * this.form.data[0] ===> setValueFromVm(this,value,'form.data[0]')
   * this.form.data[0].test ===> setValueFromVm(this,value,'form.data[0].test')
   */
  static setValueFromVm(vm, value, key = '') {
    if (typeOfUtils.isEmpty(key)) {
      return;
    }
    key = key.replace(/\[([\S\s]+?)]/g, '.$1')
    const fields = key.split('.')
    if (fields.length === 0) {
      return;
    }
    if (fields.length === 1) {
      vm.$set(vm, fields[0], value)
    } else {
      /**
       * 字段设置值
       * @param val
       * @param field
       * @param nextField
       * @return {*}
       */
      const getFieldValue = (val, field, nextField) => {
        if (/^\d+$/.test(nextField)) { // field 就是数组
          const ind = Number(nextField)
          if (typeOfUtils.isEmpty(val[field])) {
            const arr = []
            for (let i = 0; i < ind; i++) {
              // @ts-ignore
              arr.push({})
            }
            val[field] = arr
          } else { // 长度不够添加
            if (val[field].length < ind) {
              const length = ind - val[field].length
              for (let i = 0; i < length; i++) {
                val[field].push({})
              }
            }
          }
        }
        if (typeOfUtils.isNotArray(val[field]) && typeOfUtils.isEmpty(val[field])) {
          val[field] = {}
        }
        vm.$set(val, field, val[field])
        return val[field]
      }
      let val = vm
      for (let i = 0; i < fields.length - 1; i++) {
        val = getFieldValue(val, fields[i], fields[i + 1])
      }
      vm.$set(val, fields[fields.length - 1], value)
    }
  }

  /**
   * 获取子路由
   * @param router
   * @param parentPath 结尾不要带 /
   */
  static getRouteChildren(router: VueRouter, parentPath: string): RouteRecordPublic[] {
    return router.getRoutes().filter(i => {
      // @ts-ignore
      const parent = i.parent as RouteRecordPublic
      if (parent) {
        if([parentPath,parentPath+'/'].includes(parent.path)){
          return true
        }
      }
      return false
    }).filter(filterDuplicates(i => {
      const path = i.path
      if (path.endsWith('/')) {
        return path.substring(0, path.length - 1)
      }
      return path
    }))
  }

  static routerIsActive(route: Route, item: RouteRecordPublic) {
    const strings = route.path.split('/');
    const strings1 = item.path.split('/');
    for (let i = 0; i < strings1.length; i++) {
      const parent = strings1[i]
      const me = strings[i]
      if(me === undefined && parent === ""){
        return true
      }
      if(parent !== me){
        return false
      }
    }
    return true
  }
}
